import os

from PIL import Image


# 复制指定分辨率的图片到指定文件夹
# 获取图片名称
def copy_image_weight_big(file_path, new_file_path):
    for dirpath, dirnames, filenames in os.walk(file_path):
        try:
            if os.path.samefile(dirpath, new_file_path):
                continue
            for filename in filenames:
                if not filename.__contains__(".jpg") and not filename.__contains__(".png"):
                    continue
                # 获取图片路径
                iurl1 = os.path.join(dirpath, filename)
                print("iurl1:" + iurl1)
                # 打开图片
                img = Image.open(iurl1)
                # 复制宽比高分辨率大的图片
                if img.size[0] > img.size[1] and img.size[0] > 1200:
                    file = open(iurl1, "rb")
                    # 获取复制后图片路径
                    if not os.path.exists(os.path.join(new_file_path,os.path.basename(dirpath))):
                        os.makedirs(os.path.join(new_file_path,os.path.basename(dirpath)))
                    new_url = os.path.join(new_file_path,os.path.basename(dirpath), filename)
                    print("new_url:" + new_url)
                    with open(new_url, "wb+") as ff:
                        ff.write(file.read())
                        file.close()
        except Exception as e:
            print(e)
            continue

def copy_image_hight_big(file_path, new_file_path):
    for dirpath, dirnames, filenames in os.walk(file_path):
        try:
            if os.path.samefile(dirpath, new_file_path):
                continue
            for filename in filenames:
                if not filename.__contains__(".jpg") and not filename.__contains__(".png"):
                    continue
                # 获取图片路径
                iurl1 = os.path.join(dirpath, filename)
                print("iurl1:" + iurl1)
                # 打开图片
                img = Image.open(iurl1)
                # 复制宽比高分辨率大的图片
                if img.size[0] < img.size[1]:
                    file = open(iurl1, "rb")
                    if not os.path.exists(os.path.join(new_file_path,os.path.basename(dirpath))):
                        os.makedirs(os.path.join(new_file_path,os.path.basename(dirpath)))
                    # 获取复制后图片路径
                    new_url = os.path.join(new_file_path,os.path.basename(dirpath), filename)
                    print("new_url:" + new_url)
                    with open(new_url, "wb+") as ff:
                        ff.write(file.read())
                        file.close()
        except Exception as e:
            print(e)
            continue


if __name__ == '__main__':
    copy_image_weight_big(r'D:\like\picture', r'D:\like\img-weight')
    # copy_image_hight_big(r'D:\picture', r'D:\img-hight')

